<script setup lang="ts">
import {ref, watch} from 'vue'
interface ITaskItem{
  id:number;
  text:string;
  isDone:boolean;
  isEdit:boolean
}
let todoText=ref('');  //响应式对象
let taskList=ref<{id:number, text:String, isDone:boolean, isEdit:boolean}[]>([]);

taskList.value=JSON.parse(     //将字符串解析为对象的形式（反串行化）
    window.localStorage.getItem('taskList')??"[]"    //用key值去获取一个字符串，并使其非空（??"[]"如果没接收到任何东西，就将字符串替换为[]）
);

watch(taskList,onSave,{deep:true}); //检测到变化自动保存

function onAddTask() {
  taskList.value.push(
      {
        id: taskList.value.length + 1,
        text: todoText.value,
        isDone: false,
        isEdit:false
      }
  );
  todoText.value = '';
  window.localStorage
      .setItem('taskList', JSON.stringify(taskList.value));  //第一个taskList是key，可以通过这个key找到对应的值
  //将括号中的值变成用json表示的字符串（串行化）
}

function onEdit(item:ITaskItem){
  item.isEdit=true;
  itemText.value=item.text;
}

function onSave(){
  window.localStorage
      .setItem('taskList', JSON.stringify(taskList.value));
}

function onEditOk(item:ITaskItem){
  item.isEdit=false;
  item.text=itemText.value;

}

function onDelete(item:ITaskItem){
  taskList.value=taskList.value.filter(it=>it!==item); //过滤出表达式为真的函数

}

let itemText=ref('');
</script>

<template>
  <div class="container">
    <h1>ToDo List</h1>

    <div class="input-row">
      <el-input style="width: 20em" placeholder="请输入一个待办事项：..." v-model="todoText"></el-input>
      <el-button type="success" @click="onAddTask">添加</el-button>
    </div>

    <div class="task-list">
      <div v-for="item of taskList" class="task-item">
        <template v-if="!item.isEdit">
          <el-checkbox v-model="item.isDone" size="large">
            {{ item.text }}
          </el-checkbox>
          <div>
            <el-button type="primary" @click="onEdit(item)">修改</el-button>
            <el-button type="danger" @click="onDelete(item)">删除</el-button>
          </div>
        </template>
        <template v-else>
          <el-checkbox v-model="item.isDone" size="large">
            <el-input v-model="itemText"></el-input>
            <el-button type="primary" @click="onEditOk(item)">确定</el-button>
            <el-button type="danger" @click="item.isEdit=false">取消</el-button>
          </el-checkbox>
        </template>
      </div>
    </div>

  </div>
</template>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 80%;
  margin: 0 auto;
  background-color: #f3f3f3;
}

h1{
  text-align: center;
  margin-top: 20px;
}

.input-row {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  gap: 0.5em;
}


.task-list{
  padding: 0 2em;
}
.task-item{
  display: flex;
  justify-content: space-between;
  align-content: center;
  border-bottom: 1px solid #ccc;
}
</style>
